const app = getApp()
const db = wx.cloud.database()
const _ = db.command
let floor = null
let region = null
let date = ''
Page({
  data: {
    seatNum: 0
  },
  onLoad(opt) {
    console.log(opt)
    floor = opt.floor
    date = opt.date
    region = opt.region
    this.getDetail()
    wx.setNavigationBarTitle({
      title: floor + region,
    })
  },
  getDetail() {
    db.collection('venue').where({
        floor: floor,
        region: region,
        timeList: _.not(_.eq(date))
      }).get()
      .then(res => {
        console.log('可预约的座位', res)
        let list = res.data
        list.forEach(item => {
          item.selected = false
        })
        this.setData({
          list: res.data
        })
      })
  },
  // 选中的点击事件
  clickChoose(e) {
    let seatNum = 0
    let id = e.currentTarget.dataset.id
    let list = this.data.list
    list.forEach(item => {
      if (item._id == id) {
        item.selected = !item.selected
      }
      if (item.selected) {
        seatNum += 1
      }
    })
    this.setData({
      list,
      seatNum
    })
  },
  //模拟支付
  pay() {
    if (this.data.seatNum <= 0) {
      wx.showToast({
        icon: "error",
        title: '请选择座位',
      })
      return
    }
    if (this.data.seatNum > 2) {
      wx.showToast({
        icon: "error",
        title: '最多2个座位',
      })
      return
    }
    wx.showModal({
      title: "提示",
      content: "预约座位请慎重选择，如果预约后不去使用，会影响个人信用",
      confirmText: '确定预约',
      success: res => {
        if (res.confirm) {
          wx.showToast({
            title: '预约成功',
          })
          this.addOrder()
        }
      }
    })

  },
  //添加预定
  addOrder() {
    let dataList = []
    let proArr = []
    let user = app.globalData.userInfo
    this.data.list.forEach(item => {
      if (item.selected) {
        dataList.push(item._id)
        // dataList.push(item)

        console.log('item', item)
        let pro = db.collection('order').add({
          data: {
            venueFloor: floor,
            venueRegion: item.region,
            venueId: item._id,
            seat: item.seat,
            date: date,
            name: user.name,
            phone: user.phone,
            type: user.type,
            department: user.department,
            status: '待使用'
          }
        })
        proArr.push(pro)
      }
    })
    console.log(dataList)
    // wx.setStorage({
    //   key: 'yy',
    //   data: dataList
    // })
    Promise.all(proArr)
      .then(res => {
        console.log('添加预定成功', res)
        // 全部预定添加成功以后，去改变教室状态
        wx.cloud.callFunction({
          name: 'venue',
          data: {
            action: 'reserve',
            list: dataList,
            date: date
          }
        }).then(res => {
          console.log('修改教室状态结果', res)
          wx.showToast({
            title: '预定成功',
          })
          this.getDetail()
        })
      })
      .catch(res => {
        console.log('添加预定失败', res)
      })

  }
})